package org.openfans.web;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.openfans.UnauthorizedException;
import org.openfans.domain.Article;
import org.openfans.domain.Facade;
import org.openfans.domain.Fans;
import org.openfans.domain.Tag;
import org.openfans.util.ThreadFans;
import org.springframework.validation.BindException;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.SimpleFormController;

public class ArticleFormController extends SimpleFormController {
	private Facade facade = null;

	public void setFacade(Facade facade) {
		this.facade = facade;
	}

	public ArticleFormController() {
		setCommandName("article");
		setCommandClass(Article.class);
	}

	protected ModelAndView onSubmit(HttpServletRequest request,
			HttpServletResponse response, Object command, BindException errors)
			throws Exception {
		String tagId = request.getParameter("tagId");
		Article article = (Article) command;
		Fans fans = facade.getFans(ThreadFans.get().getFansId());
		Tag tag = null;
		if (null != tagId && !"".equals(tagId)) {
			tag = facade.getTag(Integer.parseInt(tagId));
		}

		facade.saveArticle(fans, article, tag);
		return new ModelAndView("redirect:viewArticle.html?id="
				+ article.getArticleId());
	}

	protected Object formBackingObject(HttpServletRequest request)
			throws Exception {
		ThreadFans.authorize();
		String articleId = request.getParameter("id");
		String tagId = request.getParameter("tagId");
		// 已有的文章
		if ((articleId != null) && !articleId.equals("0")) {
			Article article = facade.getArticle(Integer.parseInt(articleId));
			if (article.getFans().getFansId() != ThreadFans.get().getFansId()) {
				throw new UnauthorizedException("请登录");
			}
			return article;
		} else {
			Article article = new Article();
			if ((tagId != null) && !tagId.equals("")) {
				Tag tag = facade.getTag(Integer.parseInt(tagId));
				article.addTag(tag);
			}
			return article;
		}
	}
}
